package com.lib.framework.utils

import android.content.ContentResolver
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import com.bumptech.glide.Glide
import com.lib.framework.manager.ContextManager
import com.lib.framework.manager.LogManager
import java.io.ByteArrayOutputStream
import java.io.File

/**
 * Copyright (C), 2019-2020
 * FileName: BitmapUtil
 * Author: Kevin
 * Date: 2020/3/11 11:41
 * Description: 图片工具类
 * History:
 * <author> <time> <version> <desc>
 * 作者姓名 修改时间 版本号 描述
 */
class BitmapUtil {

    companion object {
        private val TAG = "BitmapUtil"

        /**
         * 从 uri 获取图片
         */
        fun getBitmapFromUri(cr: ContentResolver, uri: Uri?): Bitmap? {
            if (uri == null) return null
            var uriTmp = uri

            val imgUrl = uri.toString()
            if (imgUrl.startsWith("http")) {
                var file: File? = null
                val future = Glide.with(ContextManager.applicationContext)
                    .asFile()
                    .load(imgUrl)
                    .submit()

                try {
                    file = future.get()
                } catch (e: Exception) {
                    LogManager.e(TAG, e)
                }
                file?.let {
                    uriTmp = FileUtil.fileToUri(it)
                }
            }

            try {
                uriTmp?.let {
                    val input = cr.openInputStream(it) ?: return null
                    val bitmap = BitmapFactory.decodeStream(input)
                    input.close()
                    return bitmap
                }
            } catch (e: Exception) {
                LogManager.e(TAG, e)
            }
            return null
        }

        /**
         * bmp 转为 ByteArray
         */
        fun bmpToByteArray(bmp: Bitmap, needRecycle: Boolean): ByteArray {
            val output = ByteArrayOutputStream()
            bmp.compress(Bitmap.CompressFormat.PNG, 100, output)
            if (needRecycle) {
                bmp.recycle()
            }

            val result = output.toByteArray()
            try {
                output.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }

            return result
        }
    }

}